package com.xhorse.lockplatform.comm.util;

import com.google.gson.Gson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 封装的Gson解析工具类，提供泛型参数
 * 
 * @author qiuyafei
 * 
 */
public class GsonTransferUtil {

	/**
	 * 将Json数据解析成相应的映射对象
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T GsonToModel(String json, Class<T> type) {
		Gson gson = new Gson();
		T result = gson.fromJson(json, type);
		return result;
	}
	
	/**
	 * 将对象转换成json String
	 * @param object
	 * @return
	 */
	public static String ToJson(Object object){
		Gson gson = new Gson();
		String json = gson.toJson(object);
		return json;
	}

	/**
	 * 将加密文件进行解密并生成字符串
	 * @param filename
	 * @return
	 */
	public static String JsonfileToString(String filename) {
		File file = new File(filename);
		String key = "4c6971d6df46e89f"; //AES解密钥匙
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];  //文件原始字节数组
		try {
			FileInputStream fis = new FileInputStream(file);
			fis.read(filecontent);
			String result = DecriptUtil.decryptAES(filecontent, key);  //解密，返回最终文件json数据
			fis.close();
			return result;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
